

var ROSLIB = require('roslib');

var ros = new ROSLIB.Ros({
    url : 'ws://localhost:9090'
});

ros.on('connection', function() {
console.log('Connected to websocket server.');
});

ros.on('error', function(error) {
console.log('Error connecting to websocket server: ', error);
});

ros.on('close', function() {
console.log('Connection to websocket server closed.');
});

var cmdVel = new ROSLIB.Topic({
  ros : ros,
  name : '/control_info',
  messageType : 'std_msgs/String'
});



const cp = require('child_process');
// const py = cp.spawn('python', ['listern-easy.py'])

// py.stdout.on('data', function (res) {
//   if (!echoLock && res) {
//     echoLock = true;
//     doEcho(res).then(() => {
//       echoLock = false;
//     });
//   }
// })

let echoLock = false, catLock = false;

function writeData(data) {
 var twist = new ROSLIB.Message(data);
 cmdVel.publish(twist);
}


function getRealInput(data) {
  let res = data.match(/imx6qStart(.*?)imx6qEnd/);

  return res && res[1] ? res[1] : null;
}
function getRealOutput(data) {
  let res = 'xavierStart' + data + 'xavierEnd';

  return res;
}
function doCat() {
  const cat = cp.spawn('cat', ['/dev/ttyTHS1']);

  cat.stdout.on('data', function (data) {
    if (!catLock && data) {
      catLock = true;
      data = data.toString();
      data = getRealInput(data);
      if (data !== null) {
        console.log("xavier recev 6q", data);
        writeData(data);
        const kill = cp.spawn('kill', [cat.pid])
    }
  });

  cat.stderr.on('data', function (data) {
    console.log('cat err: ' + data);
  });

  cat.on('close', function (code) {
    console.log('cat out: ' + code);
    catLock = false;
    doCat();
  });
}

function doEcho(data) {
  data = getRealOutput(data);

  return new Promise((resolve) => cp.exec('echo ' + data + ' > /dev/ttyTHS1', function (err, stdout, stderr) {
    if (err) {
      console.error(err);
    }
    console.log("xavier send data", data);
    resolve();
  }));
}
doCat()
